package com.waitingresult.thread.sellticketdemo;

/**
 * All right reserved,Designed By WangShuai
 *
 * @author : WangShuai
 * @version : V1.0
 * @ClassName : SellTicketMain
 * @Description : 多窗口 同时 售票 的场景
 * @date : 2022/9/16 12:37
 */
public class SellTicketMain {
    public static void main(String[] args) {
        SellTicketThread1 sellTicketThread1 = new SellTicketThread1();
        //  SellTicketThread1 sellTicketThread2 = new SellTicketThread1();
        // SellTicketThread1 sellTicketThread3 = new SellTicketThread1();
//
      //  sellTicketThread1.start();
        sellTicketThread1.start();
        sellTicketThread1.start();
//        sellTicketThread2.start();
//        sellTicketThread3.start();


//        SellTicketRunnable sellTicketRunnable = new SellTicketRunnable();
//        new Thread(sellTicketRunnable).start();
//        new Thread(sellTicketRunnable).start();
//        new Thread(sellTicketRunnable).start();
    }
}

/**
 *  Thread 出现了 超卖 和重卖的问题, 因为这个 是 每new 一个SellTicketThread1 对象 都会有自己独特持有的100分数据
 */
class SellTicketThread1 extends Thread {
    public static int sellTicketNum = 100;

    private boolean whileTrueFlag = true;

    @Override
    public void run() {
        while (whileTrueFlag) {
            biz();
        }
    }

    private synchronized void biz() {
        String threadName = Thread.currentThread().getName();
        if (sellTicketNum <= 0) {
            //
            whileTrueFlag = false;
            System.err.println(threadName + " 线程 卖票结束");
            return;
        }
        //设置业务处理时间 50毫秒
        try {
            Thread.sleep(50);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        --sellTicketNum;
        System.err.println(threadName + " 线程 卖" + sellTicketNum + " 张 票, 剩余票数" + (sellTicketNum));

    }

}
/**
 *  Thread 出现了 超卖 和重卖的问题
 */
class SellTicketRunnable implements Runnable {
    public static int sellTicketNum = 100;

    private boolean whileTrueFlag = true;

    @Override
    public void run() {
        while (whileTrueFlag) {
            biz();
        }
    }

    private  void biz() {
        String threadName = Thread.currentThread().getName();
        synchronized(this){
            if (sellTicketNum <= 0) {
                whileTrueFlag = false;
                System.err.println(threadName + " 线程 卖票结束");
                return;
            }
            --sellTicketNum;

        //设置业务处理时间 50毫秒
        try {
            Thread.sleep(50);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        System.err.println(threadName + " 线程 卖" + sellTicketNum + " 张 票, 剩余票数" + (sellTicketNum));
        }
    }

}